﻿Imports System.Data
Imports System.Data.SqlClient
Imports CodeMatrix.Context
Imports System.Linq


Partial Class Apps_Default
    Inherits System.Web.UI.Page

    Protected Sub LoginButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginButton.Click
        Try
            Dim userName As String = UserNameTextBox.Text
            Dim password As String = PasswordTextBox.Text
            Dim ctx = New DataClassesDataContext()

            Dim dt As DataTable = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                "exec USP_GetStaffForLoginPage @staff_no", New SqlParameter("@staff_no", userName))

            If dt.Rows.Count > 0 Then
                Dim staff_code = dt.Rows(0)("staff_code")

                If (dt.Rows(0)("staff_fail_login") >= 3) Then
                    ' Write log
                    CodeMatrix.Business.GenericData.WriteLog(userName & " เข้าใช้งานไม่สำเร็จเนื่องจาก " & Resources.Resource.MSG_LOGIN_MAX_ATTEMP, 1, "F", staff_code)
                    Throw New Exception(Resources.Resource.MSG_LOGIN_MAX_ATTEMP)
                End If

                Dim encryptedPassword_l1 As String = ""
                Dim encryptedPassword_l2 As String = dt.Rows(0)("staff_password")
                Dim saltValue As String = dt.Rows(0)("staff_password_salt")
                Dim passPhrase = saltValue.Substring(0, 8)

                Dim rijndaelKey As New CodeMatrix.Utilities.RijndaelEnhanced(passPhrase, saltValue, 4, 8, 128, "SHA1", saltValue)
                encryptedPassword_l1 = rijndaelKey.Decrypt(encryptedPassword_l2)

                If (Convert.ToBase64String(New System.Text.UnicodeEncoding().GetBytes(password)) = encryptedPassword_l1) Then

                    If (dt.Rows(0)("staff_status") = 2 OrElse dt.Rows(0)("group_user_status") = 2 OrElse dt.Rows(0)("department_status") = 2) Then
                        ' Write log
                        CodeMatrix.Business.GenericData.WriteLog(userName & " เข้าใช้งานไม่สำเร็จเนื่องจาก " & Resources.Resource.EXCEPTION_ACCESS_DENIED, 1, "F", staff_code)
                        Throw New Exception(Resources.Resource.EXCEPTION_ACCESS_DENIED)
                    Else
                        HttpContext.Current.Session("session_id") = HttpContext.Current.Session.SessionID
                        HttpContext.Current.Session("staff_code") = staff_code
                        HttpContext.Current.Session("staff_no") = userName
                        HttpContext.Current.Session("department_code") = dt.Rows(0)("department_code")
                        HttpContext.Current.Session("department_number") = dt.Rows(0)("department_number")
                        HttpContext.Current.Session("department_name") = dt.Rows(0)("department_name")
                        HttpContext.Current.Session("department_parent") = dt.Rows(0)("department_parent")
                        HttpContext.Current.Session("master_department_name") = dt.Rows(0)("master_department_name")
                        HttpContext.Current.Session("master_department_level") = dt.Rows(0)("master_department_level")
                        HttpContext.Current.Session("group_user_code") = dt.Rows(0)("group_user_code")
                        HttpContext.Current.Session("group_user_name") = dt.Rows(0)("group_user_name")
                        HttpContext.Current.Session("group_user_type") = dt.Rows(0)("group_user_type")
                        HttpContext.Current.Session("first_name") = dt.Rows(0)("staff_firstname")
                        HttpContext.Current.Session("last_name") = dt.Rows(0)("staff_lastname")
                        HttpContext.Current.Session("staff_last_login") = dt.Rows(0)("staff_last_login")

                        Dim ip_address As String = CodeMatrix.Business.GenericData.IsOnline()
                        If ip_address = "" Then
                            ' Write log
                            CodeMatrix.Business.GenericData.WriteLog(userName & " เข้าใช้ระบบ", 1, "L", staff_code)
                            ' Reset fail login and last login date
                            CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery("UPDATE staff SET staff_fail_login = 0, staff_last_login = GETDATE(), staff_code_update = @staff_code, update_datetime = GETDATE() WHERE staff_no=@staff_no", New SqlParameter("@staff_no", userName), New SqlParameter("@staff_code", staff_code))
                            ' First time online/log off
                            CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery("exec USP_InsertOnlineStaff @staff_code, @session_id, @ip_address", _
                                    New SqlParameter("@staff_code", HttpContext.Current.Session("staff_code")), _
                                    New SqlParameter("@session_id", HttpContext.Current.Session("session_id")), _
                                    New SqlParameter("@ip_address", HttpContext.Current.Request.UserHostAddress))

                            ' Need to change password
                            If (dt.Rows(0)("staff_status_login") = 1) Then
                                HttpContext.Current.Response.Redirect("ChangePassword.aspx?scid=" & staff_code, True)
                            ElseIf (dt.Rows(0)("next_expired_date") Is System.DBNull.Value) Then
                                HttpContext.Current.Response.Redirect("ChangePassword.aspx?scid=" & staff_code, True)
                            ElseIf (Convert.ToDateTime(dt.Rows(0)("next_expired_date")).Date <= Date.Now.Date) Then
                                HttpContext.Current.Response.Redirect("ChangePassword.aspx?scid=" & staff_code, True)
                            Else
                                HttpContext.Current.Response.Redirect("welcome.aspx", True)
                            End If
                        Else
                            Throw New Exception("มีผู้ใช้งานนี้ออนไลน์อยู่ที่เครื่อง " & ip_address)
                        End If
                    End If
                Else
                    ' Write log
                    CodeMatrix.Business.GenericData.WriteLog(userName & " เข้าใช้งานไม่สำเร็จเนื่องจาก " & Resources.Resource.EXCEPTION_NO_PREVELEDGE, 1, "F", staff_code)
                    ' Increase fail login
                    CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery("UPDATE staff SET staff_fail_login = staff_fail_login + 1, staff_code_update = @staff_code, update_datetime = GETDATE() WHERE staff_no=@staff_no", New SqlParameter("@staff_no", userName), New SqlParameter("@staff_code", staff_code))
                    Throw New Exception(Resources.Resource.EXCEPTION_NO_PREVELEDGE)
                End If
            Else
                Throw New Exception(Resources.Resource.EXCEPTION_NO_PREVELEDGE)
            End If
        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try

    End Sub
End Class
